package com.hc.fdkforwarders.service.base;


import com.hc.fdkforwarders.common.AuthContext;
import com.hc.fdkforwarders.common.utils.StringUtils;
import com.hc.fdkforwarders.handler.ThreadLocalHolder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


/**
 * @author zhengbaole
 */
@Slf4j
@Service
public class BaseService implements ThreadLocalHolder {

    private static final ThreadLocal<Long> merchantIdCache = new ThreadLocal<>();
    private static final ThreadLocal<Long> userIdCache = new ThreadLocal<>();
    private static final ThreadLocal<Byte> userTypeCache = new ThreadLocal<>();
    private static final ThreadLocal<String> userNameCache = new ThreadLocal<>();
    private static final ThreadLocal<String> saleModelCache = new ThreadLocal<>();
    private static final ThreadLocal<String> nickNoCache = new ThreadLocal<>();
    private static final ThreadLocal<Long> forwarderCache = new ThreadLocal<>();
    private static final ThreadLocal<Long> sellerIdCache = new ThreadLocal<>();

    protected static final Integer FORCE_FLAG_TRUE = 1;
    public static final String SEPARATE = ":";
    /**
     * 用来记录重要日志的Logger
     **/
    protected static final Logger coreLog = LoggerFactory.getLogger("coreLog");
    /**
     * 用来在排查问题时记录临时日志的Logger，排查完后需要删除日志输出
     **/
    protected static final Logger tempLog = LoggerFactory.getLogger("tempLog");


    /**
     * @return 当前登录账号的 merchant_id
     * @author zhengbaole
     * @lastEditor zhengbaole
     * @createTime 2020/11/6 11:16 上午
     * @editTime 2020/11/6 11:16 上午
     **/
    protected Long merchantId() {
        Long merchantId = merchantIdCache.get();
        if (log.isDebugEnabled()) {
            log.debug("[Auth] merchantId cache -> {} ", merchantId);
        }
        if (merchantId == null) {
            Long acMerchantId = AuthContext.getMerchantId();
            if (log.isDebugEnabled()) {
                log.debug("[Auth] merchantId from auth context -> {} ", acMerchantId);
            }
            log.info("[Auth Token] get merchantId :{}", acMerchantId);
            return acMerchantId;
        }
        return merchantId;
    }

    /**
     * @author liuyuqing
     * @lastEditor liuyuqing
     * @createTime 2020/12/2 16:54
     * @editTime 2020/12/2 16:54
     **/
    protected void setMerchantId(Long merchantId) {
        merchantIdCache.set(merchantId);
    }


    /**
     * @author mengweibin
     * @createTime 2021/6/15 17:50
     * @editTime 2021/6/15 17:50
     */
    protected Long forwarderId() {
        Long forwarderId = forwarderCache.get();
        log.info("[Auth] get forwarderId is {}", forwarderId);
        if (log.isDebugEnabled()) {
            log.debug("[Auth] forwarderId cache -> {} ", forwarderId);
        }

        if (forwarderId == null) {
            Long acForwarderId = AuthContext.getForwarderId();
            if (log.isDebugEnabled()) {
                log.debug("[Auth] forwarderId from auth context -> {} ", acForwarderId);
            }
            log.info("[Auth Token] get token forwarderId :{}", acForwarderId);
            return acForwarderId;
        }
        return forwarderId;
    }

    /**
     * @author mengweibin
     * @createTime 2021/6/15 18:15
     * @editTime 2021/6/15 18:15
     */
    protected void setForwarderId(Long forwarderId) {
        forwarderCache.set(forwarderId);
    }


    /**
     * @return 当前登录用户的 uid
     * @author zhengbaole
     * @lastEditor zhengbaole
     * @createTime 2020/11/13 3:34 下午
     * @editTime 2020/11/13 3:34 下午
     **/
    public Long userId() {
        Long uid = userIdCache.get();
        if (uid == null) {
            return AuthContext.getUserId();
        }
        return uid;
    }

    /**
     * @author liuyuqing
     * @lastEditor liuyuqing
     * @createTime 2020/12/2 16:54
     * @editTime 2020/12/2 16:54
     **/
    protected void setUserId(Long userId) {
        userIdCache.set(userId);
    }

    /**
     * 获取当前登录账号的 名称
     *
     * @return user_name
     * @author wangmingliang
     * @lastEditor weike
     * @createTime 2020/11/13 11:16 上午
     * @editTime 2020-12-24 17:51:43
     **/
    protected String userName() {
        String userName = userNameCache.get();
        if (log.isDebugEnabled()) {
            log.debug("[Auth] userName cache -> {} ", userName);
        }
        if (userName == null) {
            String acUserName = AuthContext.getUserName();
            if (log.isDebugEnabled()) {
                log.debug("[Auth] userName from auth context -> {} ", acUserName);
            }
            return acUserName;
        }
        return userName;
    }


    /**
     * @author liuyuqing
     * @lastEditor liuyuqing
     * @createTime 2020/12/2 16:54
     * @editTime 2020/12/2 16:54
     **/
    protected void setUserName(String userName) {
        userNameCache.set(userName);
    }

    protected MerchantInfoDTO getMerchantInfoDTO() {
        MerchantInfoDTO merchantInfoDTO = new MerchantInfoDTO();
        merchantInfoDTO.setMerchantId(merchantId());
        merchantInfoDTO.setUserId(userId());
        merchantInfoDTO.setUserName(userName());
        merchantInfoDTO.setSaleMode(saleModelType());
        merchantInfoDTO.setNickNo(nickNo());
        merchantInfoDTO.setUserType(userType());
        merchantInfoDTO.setForwarderId(forwarderId());
        return merchantInfoDTO;
    }

    protected void setMerchantInfoDTO(MerchantInfoDTO merchantInfoDTO) {
        setMerchantId(merchantInfoDTO.getMerchantId());
        setUserId(merchantInfoDTO.getUserId());
        setUserName(merchantInfoDTO.getUserName());
        setSaleModelType(merchantInfoDTO.getSaleMode());
        setNickNo(merchantInfoDTO.getNickNo());
        setUserType(merchantInfoDTO.getUserType());
        setForwarderId(merchantInfoDTO.getForwarderId());
    }


    /**
     * 设置销售模式
     *
     * @param saleModel 发得快销售模式
     */
    protected void setSaleModelType(String saleModel) {
        saleModelCache.set(saleModel);
    }


    /**
     * 获取销售模式
     *
     * @return saleModel 发得快销售模式
     */
    protected String saleModelType() {
        String saleMode = saleModelCache.get();
        if (StringUtils.isEmpty(saleMode)) {
            saleMode = AuthContext.getFenxiaoModelType();
            // 如果token中不带该参数，默认自销模式
            if (StringUtils.isEmpty(saleMode)) {
                saleMode = AuthContext.MODEL_TYPE_SELF_SALE;
            }
        }
        return saleMode;
    }

    /**
     * 缓存 nick_no 到 thread local
     */
    protected void setNickNo(String nickNo) {
        nickNoCache.set(nickNo);
    }

    /**
     * 获取分销商 nick_no
     */
    protected String nickNo() {
        String nickNo = AuthContext.nickNo();

        if (StringUtils.isEmpty(nickNo)) {
            nickNo = nickNoCache.get();
        }

        return nickNo;
    }


    /**
     * 设置merchantInfoDTO并返回
     *
     * @return merchantInfoDTO
     */
    protected MerchantInfoDTO cacheMerchantInfoDTO() {
        MerchantInfoDTO merchantInfoDTO = getMerchantInfoDTO();
        setMerchantInfoDTO(merchantInfoDTO);
        return merchantInfoDTO;
    }

    protected void setUserType(Byte userType) {
        userTypeCache.set(userType);
    }

    protected Byte userType() {
        Byte userType = AuthContext.getUserType();

        if (null == userType) {
            userType = userTypeCache.get();
        }

        return userType;
    }


    /**
     * 获取代拿端回调的sellerId
     */
    protected Long sellerId() {
        Long sellerId = sellerIdCache.get();
        if (log.isDebugEnabled()) {
            log.debug("[Auth] sellerId cache -> {} ", sellerId);
        }
        if (sellerId == null) {
            sellerId = AuthContext.getSellerId();
            if (log.isDebugEnabled()) {
                log.debug("[Auth] sellerId from auth context -> {} ", sellerId);
            }
            log.info("[Auth Token] get sellerId :{}", sellerId);
        }
        return sellerId;
    }


    /**
     * 缓存sellerId
     */
    protected void setSellerId(Long sellerId) {
        sellerIdCache.set(sellerId);
    }



    @Override
    public void onContextClosed() {
        merchantIdCache.remove();
        userIdCache.remove();
        userTypeCache.remove();
        userNameCache.remove();
        saleModelCache.remove();
        nickNoCache.remove();
        sellerIdCache.remove();
        forwarderCache.remove();
    }
}
